using System;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;

namespace DA.AnimGraph.Editor {

    internal class InspectorField_ClipLink : InspectorField<AGAFieldModel_ClipLink> {

        ObjectField clipField;

        protected override void BuildUI() {
            clipField = new ObjectField(labelText);
            clipField.objectType = typeof(AnimationClip);
            if (ageContext.resourceManager.GetResource(source.clipKey, out var entry)) {
                clipField.value = entry.resource;
            }
            clipField.RegisterValueChangedCallback(OnClipChange);
        }

        protected override void DrawUI() {
            Add(clipField);
        }

        private void OnClipChange(ChangeEvent<UnityEngine.Object> evt) {
            if (evt.previousValue != null) {
                ageContext.resourceManager.TryRemoveResource(source.clipKey);
                source.clipKey = default;
            }
            if (evt.newValue != null) {
                var uuid = ageContext.resourceManager.AddResource(evt.newValue, AGAResourceType.Clip);
                source.clipKey = uuid;
            }

            inspectorChangeCallback?.Invoke();
        }

        public AnimationClip GetClip() {
            return clipField.value as AnimationClip;
        }
    }

}
